package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件服务实现类
 * 实现了文件上传功能，使用MinIO对象存储服务
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient; // 注入MinIO客户端
    @Autowired
    private MinioProperties properties; // 注入MinIO配置属性

    /**
     * 上传文件方法
     * @param file 要上传的文件
     * @return 文件的访问URL
     */
    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 检查存储桶是否存在，不存在则创建
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().
                    bucket(properties.getBucketName()).build());
            if (!bucketExists) {
            // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
            // 设置存储桶策略，允许公开访问
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(properties.getBucketName())
                        .config(createBucketPolicyConfig(properties.getBucketName())).build());
            }
        // 生成文件名：日期/UUID-原始文件名
            String filename = new SimpleDateFormat("yyyyMMdd").format
                    (new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
        // 上传文件到MinIO
            minioClient.putObject(PutObjectArgs.builder().bucket(properties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1).object(filename)
                    .contentType(file.getContentType()).build());
        // 返回文件的访问URL
            return String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);


    }

    /**
     * 创建存储桶策略配置
     * @param bucketName 存储桶名称
     * @return JSON格式的存储桶策略配置字符串
     */
    private String createBucketPolicyConfig(String bucketName) {

        // 使用模板字符串生成存储桶策略配置
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}

